//============================================================================
// Name        : Run.cpp
// Author      : lucmir@dcc.ufmg.br
// Description :
//============================================================================

#include "Run.h"


Run::Run() {
	this->registryCount = 0;
}

Run::~Run() {
	this->clear();
}

void Run::insert(unsigned int docId, unsigned int termId) {
	std::map<unsigned int, std::list<TermInfo *> >::iterator itr = this->registrySet.find(termId);
	TermInfo *back;

	if(itr != this->registrySet.end()) {
		back = itr->second.back();
		if(back->getDocId() == docId) {
			back->incFreq();
		}
		// First entry for docId
		else {
			itr->second.push_back(new TermInfo(docId));
			this->registryCount++;
		}
	}
	// First entry for this termId
	else {
		std::list<TermInfo *> list;
		list.push_back(new TermInfo(docId));
		this->registrySet[termId] = list;
		this->registryCount++;
	}

}

unsigned int Run::getLen() {
	return this->registryCount;
}

void Run::clear() {
	this->registrySet.clear();
}

void Run::printToFile(std::string fileName, Lexon *lexon) {
	std::ofstream file;
	TermInfo *r;
	unsigned int termId;
	std::map<unsigned int, std::list<TermInfo *> >::iterator itr = this->registrySet.begin();
	std::list<TermInfo *>::iterator litr;

	file.open(fileName.c_str());
	bool first = true;
	for(; itr != this->registrySet.end(); itr++) {
		for(litr = itr->second.begin(); litr != itr->second.end(); litr++) {
			r = *litr;
			termId = itr->first;
			if(first) {
				file << termId << " " << r->getDocId() << " " << r->getFreq();
				first = false;
			}
			else {
				file << "\n" << termId << " " << r->getDocId() << " " << r->getFreq();
			}

			// Increment Term Frequency
			lexon->incTf(termId);

			delete r;
		}
	}
	this->clear();
	this->registryCount = 0;
	file.close();
}

bool Run::readFromFile(std::ifstream &file, Registry &registry) {
	std::string line;
	int value;

	if (file.is_open() and !file.eof()) {
		getline(file, line);
		std::istringstream istr(line);
		istr >> value;
		registry.setTermId(value);
		istr >> value;
		registry.setDocId(value);
		istr >> value;
		registry.setFreq(value);
		return true;
	}
	return false;
}


#ifdef RUN_TEST

// Unit test
int main(int argc, char** argv) {
	Run *run = new Run();
	run->insert(1, 1);
	std::cout << run->getLen() << "\n";
	run->insert(1, 2);
	std::cout << run->getLen() << "\n";
	run->insert(1, 2);
	std::cout << run->getLen() << "\n";
	run->insert(1, 2);
	std::cout << run->getLen() << "\n";
	run->insert(1, 3);
	std::cout << run->getLen() << "\n";
	run->insert(2, 3);
	std::cout << run->getLen() << "\n";
	run->insert(2, 2);
	std::cout << run->getLen() << "\n";
	run->insert(3, 4);
	std::cout << run->getLen() << "\n";
	run->insert(3, 1);
	std::cout << run->getLen() << "\n";
	run->printToFile(std::string("/tmp/dugu"));
}

#endif
